/* 按钮权限 */
import { useAuthStore } from '@/stores';

// v-hasPermi="['system:user:create']" 使用
export function hasPermi(app) {
    app.directive("hasPermi", (el, binding) => {
        const { permissions } = useAuthStore();
        const { value } = binding;
        const all_permission = "*:*:*";
        if (value && value instanceof Array && value.length > 0) {
            const permissionFlag = value;
            const hasPermissions = permissions.some((permission) => {
                return all_permission === permission || permissionFlag.includes(permission);
            });
            if (!hasPermissions) {
                el.parentNode && el.parentNode.removeChild(el);
            }
        } else {
            throw new Error("权限不存在");
        }
    });
}

// import { checkPermi } from '@/permission/btnPermission.js';
// v-if="checkPermi(['system:tabs:first'])"
export function checkPermi(value) {
    const { permissions } = useAuthStore();
    const all_permission = "*:*:*";
    if (value && value instanceof Array && value.length > 0) {
        const permissionFlag = value;
        const hasPermissions = permissions.some((permission) => {
            return all_permission === permission || permissionFlag.includes(permission);
        });
        if (!hasPermissions) {
            return false;
        }
        return true;
    }
}

export const setupAuth = (app) => {
    hasPermi(app);
};
